import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'

import { constantRouter } from './constantRouter'
import useMainStore from '@/stores/index'

import { toast } from '@/utils/common'
import { getLocal } from '@/utils/localStorage'

import { logout } from '@/views/login/store'

let speed = 300 // 进度条速度，加载状态速度

NProgress.configure({
    easing: 'ease-in-out',
    speed,
    showSpinner: false,
    trickleSpeed: 200,
    minimum: 0.3
})

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRouter as any
})

router.beforeEach(async (to, from) => {
    const userStore = useMainStore().useUserStore()
    const LayoutStore = useMainStore().useLayoutStore()
    const token = getLocal('token')
    let keysLength = Object.keys(token).length

    LayoutStore.spinning = true // 开启loading
    NProgress.start() //开启进度条

    if (keysLength) {
        if (Object.keys(userStore.userInfo).length <= 0) {
            try {
                await userStore.getUserInfo(token) //这里会处理错误
            } catch (e) {
                return { name: 'login' }
            }
        } else if (to.name === 'login' && Object.keys(userStore.userInfo).length > 0) {
            return { name: '/' }
        }
    } else {
        if (to.name !== 'login') {
            toast('error', '', '请先登录')
            logout() //退出登录，避免后端数据不同步
            return { name: 'login' }
        }
    }
})

router.afterEach((to, from) => {
    const LayoutStore = useMainStore().useLayoutStore()
    setTimeout(() => {
        LayoutStore.spinning = false // 关闭loading
    }, speed)
    NProgress.done() //关闭进度条
})

export default router
